<template>
  <div class="zzddj">
    

    <DaoHanginPage/>
    
    <!-- 产地信息 -->
    <div class="area-info">
      <h3 class="title">产地信息</h3>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产地名称" prop="area_name">
              <el-input v-model="form.area_name" placeholder="请输入产地名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="产地地点" required>
                <div style="display: flex; flex-wrap: wrap; gap: 10px;">
                  <el-form-item prop="province" style="flex: 1;">
                    <el-select v-model="form.province" placeholder="请选择省份" @change="handleProvinceChange">
                      <el-option
                        v-for="province in provinces"
                        :key="province.code"
                        :label="province.name"
                        :value="province.code"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item prop="city" style="flex: 1;">
                    <el-select v-model="form.city" placeholder="请选择城市" @change="handleCityChange" :disabled="!form.province">
                      <el-option
                        v-for="city in cities"
                        :key="city.code"
                        :label="city.name"
                        :value="city.code"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item prop="district" style="flex: 1;">
                    <el-select v-model="form.district" placeholder="请选择区县" @change="handleDistrictChange" :disabled="!form.city">
                      <el-option
                        v-for="district in districts"
                        :key="district.code"
                        :label="district.name"
                        :value="district.code"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item prop="detail_address" style="width: 100%; margin-top: 10px;">
                    <el-input v-model="form.detail_address" placeholder="请输入街道以及门牌号" />
                  </el-form-item>
                </div>
              </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产地面积" prop="area_acreage">
              <div class="area-input-group">
                <el-input v-model="form.area_acreage" placeholder="请输入产地面积" />
                <el-select v-model="form.acreage_kind" placeholder="面积单位">
                  <el-option label="亩" value="亩" />
                  <el-option label="公顷" value="公顷" />
                  <el-option label="平方米" value="平方米" />
                </el-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="土壤类型" prop="land_kind">
              <el-select v-model="form.land_kind" placeholder="请选择土壤类型">
                <el-option label="耕地" value="耕地" />
                <el-option label="林地" value="林地" />
                <el-option label="草地" value="草地" />
                <el-option label="园地" value="园地" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
         
          <el-col :span="12">
            <el-form-item label="土地负责人" prop="responsible_person">
              <el-input v-model="form.responsible_person" placeholder="请输入土地负责人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contact_phone">
              <el-input v-model="form.contact_phone" placeholder="请输入联系电话" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="产地图片" prop="area_image">
              <ImageUpload 
                v-model="form.area_image"
                :limit="5"
                :file-size="5"
                :file-type="['jpg', 'jpeg', 'png', 'gif']"
                action="/common/upload"
                @update:modelValue="handleImageChange"
                @error="handleImageError"
              />
              <div class="upload-tips">
                <el-icon><InfoFilled /></el-icon>
                <span>请上传产地相关图片，支持jpg、jpeg、png、gif格式，单张图片不超过5MB，最多上传5张</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row justify="end">
        <el-col :span="3">
          <button @click="getMassage" class="btn2">提交</button>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import DaoHanginPage from '@/components/ncpsy/ZSPT/DaoHanginPage/DaoHanginPage.vue'
import ImageUpload from '@/components/ImageUpload/index.vue'
import { ref, onMounted, reactive } from 'vue'
import { addArea } from '@/api/ncpsy/management/area'
import { InfoFilled } from '@element-plus/icons-vue'

import useUserStore from '@/store/modules/user'
import { ElMessage } from 'element-plus';
const userStore = useUserStore()
const userId = userStore.id;

// 省市区数据
const provinces = ref([]);
const cities = ref([]);
const districts = ref([]);

// 产地信息
const formRef = ref(null);
const form = reactive({
  area_name: '', // 产地名称
  province: '', // 省份代码
  city: '', // 城市代码
  district: '', // 区县代码
  detail_address: '', // 详细地址
  area_acreage: '', // 产地面积
  acreage_kind: '', // 面积单位
  land_kind: '', // 土壤类型
  area_status: '闲置', // 产地状态
  responsible_person: '', // 土地负责人
  contact_phone: '', // 联系电话
  area_image: '' // 添加图片字段
})

const rules = ref({
  area_name: [{ required: true, message: '请输入产地名称', trigger: 'blur' }],
  province: [{ required: true, message: '请选择省份', trigger: 'change' }],
  city: [{ required: true, message: '请选择城市', trigger: 'change' }],
  district: [{ required: true, message: '请选择区县', trigger: 'change' }],
  detail_address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
  area_acreage: [
    { required: true, message: '请输入产地面积', trigger: 'blur' },
    { pattern: /^\d+(\.\d+)?$/, message: '产地面积只能为数字', trigger: 'blur' }
  ],
  acreage_kind: [{ required: true, message: '请选择面积单位', trigger: 'change' }],
  land_kind: [{ required: true, message: '请选择土壤类型', trigger: 'change' }],
  responsible_person: [{ required: true, message: '请输入土地负责人姓名', trigger: 'blur' }],
  contact_phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
});

// 省份变化处理
const handleProvinceChange = (provinceCode) => {
  // 重置城市和区县
  form.city = '';
  form.district = '';
  cities.value = [];
  districts.value = [];
  
  // 查找选中省份的城市列表
  const selectedProvince = provinces.value.find(p => p.code === provinceCode);
  if (selectedProvince && selectedProvince.children) {
    cities.value = selectedProvince.children;
  }
};

// 城市变化处理
const handleCityChange = (cityCode) => {
  // 重置区县
  form.district = '';
  districts.value = [];
  
  // 查找选中城市的区县列表
  const selectedCity = cities.value.find(c => c.code === cityCode);
  if (selectedCity && selectedCity.children) {
    districts.value = selectedCity.children;
  }
};

// 区县变化处理
const handleDistrictChange = () => {
  // 区县变化时的处理，如果需要可以在这里添加逻辑
};

// 获取完整地址
const getFullAddress = () => {
  let address = '';
  
  // 获取省份名称
  if (form.province) {
    const province = provinces.value.find(p => p.code === form.province);
    if (province) address += province.name;
  }
  
  // 获取城市名称
  if (form.city) {
    const city = cities.value.find(c => c.code === form.city);
    if (city) address += city.name;
  }
  
  // 获取区县名称
  if (form.district) {
    const district = districts.value.find(d => d.code === form.district);
    if (district) address += district.name;
  }
  
  // 添加详细地址
  if (form.detail_address) {
    address += form.detail_address;
  }
  
  return address;
};

// 图片上传变化处理
const handleImageChange = (value) => {
  form.area_image = value;
  console.log('图片已更新:', value);
};

// 图片上传错误处理
const handleImageError = (error) => {
  console.error('图片上传错误:', error);
  ElMessage.error('图片上传失败，请重试或联系管理员');
};

// 获取信息方法
const getMassage = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 构建请求数据
      const areaData = {
        userId: userId,
        areaName: form.area_name,
        areaAddress: getFullAddress(), // 使用组合后的完整地址
        areaAcreage: form.area_acreage,
        acreageKind: form.acreage_kind,
        landKind: form.land_kind,
        areaStatus: form.area_status,
        responsiblePerson: form.responsible_person,
        contactPhone: form.contact_phone,
        areaImage: form.area_image // 添加图片字段
      };
      
      // 调用API接口
      try {
        const response = await addArea(areaData);
        console.log('添加产地信息成功:', response);
        ElMessage.success('添加产地信息成功！');
        resetForm();
      } catch (error) {
        console.error('添加产地信息失败:', error);
        ElMessage.error('添加失败，请检查输入信息！');
      }
    }
  });
};

// 重置表单方法
const resetForm = () => {
  formRef.value.resetFields();
  form.area_name = ''; // 产地名称
  form.province = ''; // 省份代码
  form.city = ''; // 城市代码
  form.district = ''; // 区县代码
  form.detail_address = ''; // 详细地址
  form.area_acreage = ''; // 产地面积
  form.acreage_kind = '亩'; // 面积单位
  form.land_kind = ''; // 土壤类型
  form.area_status = '闲置'; // 产地状态
  form.responsible_person = ''; // 土地负责人
  form.contact_phone = ''; // 联系电话
  form.area_image = ''; // 图片字段
  
  // 清空城市和区县选项
  cities.value = [];
  districts.value = [];
};

// 组件挂载时异步加载省市区数据
onMounted(async () => {
  try {
    // 使用fetch API加载location.json文件
    const response = await fetch('/json/location.json');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const locationData = await response.json();
    provinces.value = locationData;
    console.log('省市区数据加载成功，共', locationData.length, '个省份');
  } catch (error) {
    console.error('加载省市区数据失败:', error);
    // 如果加载失败，可以使用一个简单的默认数据
    provinces.value = [
      { code: '11', name: '北京市', children: [{ code: '1101', name: '市辖区', children: [] }] },
      { code: '31', name: '上海市', children: [{ code: '3101', name: '市辖区', children: [] }] },
      { code: '44', name: '广东省', children: [{ code: '4401', name: '广州市', children: [] }] }
    ];
  }
});
</script>

<style scoped>
.zzddj{
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 产地信息样式 */
.area-info {
  background-color: #ffffff;
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 2px 10px rgba(209, 209, 209, 0.3);
  margin-bottom: 20px;
}

.title {
  font-size: 24px;
  font-weight: 600;
  text-align: left;
  margin-bottom: 25px;
  color: #303133;
  border-bottom: 2px solid #e4e7ed;
  padding-bottom: 15px;
}

.form-item {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  text-align: left;
  margin-bottom: 8px;
  font-size: 16px;
  color: #606266;
  width: 100px;
}

.required {
  color: #f56c6c;
}

/* 面积输入组样式 */
.area-input-group {
  display: flex;
  gap: 10px;
}

.area-input-group .el-input {
  flex: 1;
}

.area-input-group .el-select {
  width: 100px;
}

/* 省市区选择器样式 */
.area-selector {
  display: flex;
  gap: 0;
  margin-bottom: 10px;
}

.area-selector .el-select {
  flex: 1;
}

/* 按钮区域样式 */
.btndiv{
  border-radius: 10px;
  background-color: #ffffff;
  line-height: 70px;
  box-shadow: 0 10px 10px rgba(192, 191, 191, 0.58);
  padding: 0 30px;
  margin-top: 20px;
}

.btn1,.btn2{
  font-size: 16px;
  border: none;
  width: 120px;
  height: 40px;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn1{
  background-color: #f3f4f6;
  color: #4d5765;
  margin-right: 15px;
}

.btn1:hover {
  background-color: #e9ebee;
}

.btn2{
  background-color: #2e7d32;
  color: #ffffff;
}

.btn2:hover {
  background-color: #1f5e23;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-col-12 {
    width: 100%;
  }
  
  .btn1, .btn2 {
    width: 100%;
    margin-bottom: 10px;
  }
}

/* 图片上传组件样式优化 */
.component-upload-image {
  width: 100%;
}

/* 上传区域样式 */
.component-upload-image :deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
  line-height: 120px;
  border: 2px dashed #c0ccda;
  border-radius: 8px;
  background-color: #fafafa;
  transition: all 0.3s ease;
}

.component-upload-image :deep(.el-upload--picture-card:hover) {
  border-color: #409eff;
  background-color: #f0f9ff;
}

/* 上传图标样式 */
.component-upload-image :deep(.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  transition: all 0.3s ease;
}

.component-upload-image :deep(.el-upload--picture-card:hover .avatar-uploader-icon) {
  color: #409eff;
  transform: scale(1.1);
}

/* 图片列表样式 */
.component-upload-image :deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.component-upload-image :deep(.el-upload-list--picture-card .el-upload-list__item:hover) {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
}

/* 上传提示文字样式 */
.component-upload-image :deep(.el-upload__tip) {
  font-size: 13px;
  color: #909399;
  margin-top: 8px;
  text-align: left;
}

/* 预览对话框样式 */
.component-upload-image :deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

.component-upload-image :deep(.el-dialog__header) {
  background-color: #f5f7fa;
  padding: 15px 20px;
  border-bottom: 1px solid #e4e7ed;
}

.component-upload-image :deep(.el-dialog__body) {
  padding: 20px;
  background-color: #fff;
}

/* 加载状态样式 */
.component-upload-image :deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .component-upload-image :deep(.el-upload--picture-card),
  .component-upload-image :deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }
  
  .component-upload-image :deep(.avatar-uploader-icon) {
    font-size: 24px;
  }
}

/* 上传提示区域样式 */
.upload-tips {
  display: flex;
  align-items: center;
  margin-top: 8px;
  padding: 8px 12px;
  background-color: #f0f9ff;
  border-left: 4px solid #409eff;
  border-radius: 4px;
  font-size: 13px;
  color: #606266;
  line-height: 1.5;
}

.upload-tips .el-icon {
  margin-right: 8px;
  color: #409eff;
  font-size: 16px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .upload-tips {
    font-size: 12px;
    padding: 6px 10px;
  }
  
  .upload-tips .el-icon {
    font-size: 14px;
    margin-right: 6px;
  }
}
</style>